package model

import (
	"ginBasic/app/common/lib"
	"ginBasic/global"
)

var ManagerModel = new(Manager)

type Manager struct {
	Id         int    `form:"id" json:"id"`
	Username   string `form:"username" json:"username"`
	Password   string `form:"password" json:"-"`
	Mobile     string `form:"mobile" json:"mobile"`
	Email      string `form:"email" json:"email"`
	Status     int    `form:"status" json:"status"`
	RoleId     int    `form:"role_id" json:"role_id"`
	AddTime    int    `form:"add_time" json:"add_time"`
	UpdateTime int    `form:"update_time" json:"update_time"`
	IsSuper    int    `form:"-" json:"-"`
	Role       Role   `grom:"foreignKey:RoleId,references:Id"`
}

func (Manager) TableName() string {
	return "manager"
}

func (Manager) List(where string, page, pageSize int) ([]Manager, int, error) {

	managerList := []Manager{}
	err := global.DB.Preload("Role").Where(where).Scopes(Paginate(page, pageSize)).Find(&managerList).Error
	if err != nil {
		return nil, 0, err
	}
	//获取总条数
	var total int64
	global.DB.Model(&Manager{}).Where(where).Count(&total)
	return managerList, int(total), nil

}

func (Manager) Add(req *Manager) (bool, error) {
	manager := Manager{
		Username:   req.Username,
		Password:   lib.Md5(req.Password),
		Mobile:     req.Mobile,
		Email:      req.Email,
		Status:     req.Status,
		RoleId:     req.RoleId,
		AddTime:    int(lib.GetUnix()),
		UpdateTime: int(lib.GetUnix()),
	}
	err := global.DB.Create(&manager).Error
	if err != nil {
		return false, err
	}
	return true, nil
}

func (Manager) Edit(req *Manager) (bool, error) {
	manager := Manager{Id: req.Id}
	global.DB.Find(&manager)
	if req.Password != "" {
		manager.Password = lib.Md5(req.Password)
	}
	manager.Username = req.Username
	manager.Mobile = req.Mobile
	manager.Email = req.Email
	manager.Status = req.Status
	manager.RoleId = req.RoleId
	manager.UpdateTime = int(lib.GetUnix())
	err := global.DB.Save(&manager).Error
	if err != nil {
		return false, err
	}
	return true, nil
}

// 根据username返回用户信息
func (Manager) GetUserByUsername(username string) Manager {
	var manager Manager
	global.DB.Where("username=?", username).Find(&manager)
	return manager
}

// 根据id返回用户信息
func (Manager) GetUserById(id int) Manager {
	var manager Manager
	global.DB.Where("id=?", id).Find(&manager)
	return manager
}

func (Manager) Delete(ids []string) (bool, error) {

	res := global.DB.Delete(&Manager{}, ids)
	if res.Error != nil {
		//记录删除报错的原因 TODO
		return false, res.Error
	}
	return true, nil
}

func (Manager) UpdateStatus(req *Manager) (bool, error) {
	manager := Manager{Id: req.Id}
	global.DB.Find(&manager)
	manager.Status = req.Status
	err := global.DB.Save(&manager).Error
	if err != nil {
		// TODO 保存到日志文件
		return false, err
	}
	return true, nil
}
